package com.ewanghuiju.app.ui.my.activity;

import android.Manifest;
import android.content.Intent;
import android.content.pm.ActivityInfo;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.graphics.Color;
import android.graphics.drawable.GradientDrawable;
import android.os.Build;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.Gravity;
import android.view.View;
import android.view.animation.Animation;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.azhon.appupdate.config.UpdateConfiguration;
import com.azhon.appupdate.manager.DownloadManager;
import com.bumptech.glide.Glide;
import com.bumptech.glide.load.engine.DiskCacheStrategy;
import com.ewanghuiju.app.R;
import com.ewanghuiju.app.app.App;
import com.ewanghuiju.app.app.Constants;
import com.ewanghuiju.app.base.BaseActivity;
import com.ewanghuiju.app.base.contract.my.MyContract;
import com.ewanghuiju.app.component.ACache;
import com.ewanghuiju.app.component.RxBus;
import com.ewanghuiju.app.jpush.TagAliasOperatorHelper;
import com.ewanghuiju.app.model.bean.response.LbImgBean;
import com.ewanghuiju.app.model.bean.response.OrderStatusResponBean;
import com.ewanghuiju.app.model.bean.response.UserInfoResponBean;
import com.ewanghuiju.app.model.bean.response.VersionResponBean;
import com.ewanghuiju.app.model.dp.RealmHelper;
import com.ewanghuiju.app.model.event.SendEvent;
import com.ewanghuiju.app.model.http.response.BaseResponse;
import com.ewanghuiju.app.model.prefs.ImplPreferencesHelper;
import com.ewanghuiju.app.presenter.my.MyPresenter;
import com.ewanghuiju.app.ui.login.activity.LoginMainActivity;
import com.ewanghuiju.app.ui.pintuan.adapter.pictureselector.GlideEngine;
import com.ewanghuiju.app.util.LoadingDialogUtils;
import com.ewanghuiju.app.util.LogUtil;
import com.ewanghuiju.app.util.StartActivityUtil;
import com.ewanghuiju.app.util.nodoubleclick.AntiShake;
import com.ewanghuiju.app.util.oss.OssManager;
import com.ewanghuiju.app.widget.popupwindow.CustomBasePopup;
import com.ewanghuiju.app.widget.popupwindow.PicSelectedPopup;
import com.ewanghuiju.app.widget.popupwindow.PopupItemClickCallback;
import com.ewanghuiju.app.widget.popupwindow.UnbindwxBasePopup;
import com.gyf.immersionbar.ImmersionBar;
import com.luck.picture.lib.PictureSelector;
import com.luck.picture.lib.config.PictureConfig;
import com.luck.picture.lib.config.PictureMimeType;
import com.luck.picture.lib.entity.LocalMedia;
import com.luck.picture.lib.listener.OnResultCallbackListener;
import com.luck.picture.lib.permissions.PermissionChecker;
import com.luck.picture.lib.style.PictureParameterStyle;
import com.luck.picture.lib.tools.DateUtils;
import com.luck.picture.lib.tools.PictureFileUtils;
import com.makeramen.roundedimageview.RoundedImageView;
import com.muddzdev.styleabletoast.StyleableToast;
import com.umeng.socialize.UMAuthListener;
import com.umeng.socialize.UMShareAPI;
import com.umeng.socialize.UMShareConfig;
import com.umeng.socialize.bean.SHARE_MEDIA;

import java.io.File;
import java.util.List;
import java.util.Map;

import androidx.core.content.ContextCompat;
import butterknife.BindView;
import butterknife.OnClick;

import static com.ewanghuiju.app.jpush.TagAliasOperatorHelper.ACTION_DELETE;
import static com.ewanghuiju.app.jpush.TagAliasOperatorHelper.sequence;


/**
 * @author sj  qq:751943509
 * @class 设置页面     下载监听, OnDownloadListener, OnButtonClickListener
 * @time 2020/2/24
 */
public class SettingActivity extends BaseActivity<MyPresenter> implements MyContract.View {

    @BindView(R.id.tv_login_out)
    TextView tvLoginOut;
    @BindView(R.id.tv_cache_text)
    TextView tvCacheText;
    //微信号
    @BindView(R.id.tv_bindwx_lab)
    TextView tvBindwxLab;
    //支付宝
    @BindView(R.id.tv_bindzfb_lab)
    TextView tvBindzfbLab;
    @BindView(R.id.riv_user_head)
    RoundedImageView rivUserHead;
    @BindView(R.id.tv_nickname_lab)
    TextView tvNicknameLab;
    @BindView(R.id.tv_phone_number_lab)
    TextView tvPhoneNumberLab;
    @BindView(R.id.tv_sh_info_lab)
    TextView tvShInfoLab;
    @BindView(R.id.tv_login_pwd_lab)
    TextView tvLoginPwdLab;
    @BindView(R.id.tv_pay_password)
    TextView tvPayPassword;
    @BindView(R.id.tv_settingwx_lab)
    TextView tvSettingwxLab;
    @BindView(R.id.layout_setting_wx)
    LinearLayout layoutSettingWx;
    @BindView(R.id.tv_version)
    TextView tvVersion;

    private File cacheFile;

    private CustomBasePopup customBasePopup;
    private UnbindwxBasePopup unbindwxBasePopup;
    private PicSelectedPopup picSelectedPopup;
    private PictureParameterStyle mPictureParameterStyle;

    @Override
    protected int getLayout() {
        return R.layout.activity_setting;
    }

//    private UserInfoResponBean userInfoResponBean;

    private String headUrl = "";

    @Override
    protected void initEventAndData() {
        cacheFile = new File(Constants.PATH_CACHE);
        tvCacheText.setText(ACache.getCacheSize(cacheFile));

        GradientDrawable gradientDrawable = (GradientDrawable) tvLoginOut.getBackground();
        gradientDrawable.setStroke(1, ContextCompat.getColor(mContext, R.color.color_ccc));
        mPresenter.getData();

        try {
            PackageManager pm = mContext.getPackageManager();
            PackageInfo pi = pm.getPackageInfo(mContext.getPackageName(), PackageManager.GET_ACTIVITIES);
            tvVersion.setText("V" + pi.versionName);
        } catch (PackageManager.NameNotFoundException e) {
            e.printStackTrace();
        }
    }

    @Override
    protected void initView(Bundle savedInstanceState) {
        super.initView(savedInstanceState);
        if (savedInstanceState != null) {
            // 被回收
        } else {
            clearCache();
        }
        getDefaultStyle();
    }

    @OnClick({R.id.layout_bind_wx,
            R.id.layout_hide_set, R.id.layout_nickname, R.id.layout_login_pwd, R.id.layout_setting_wx, R.id.layout_vesion,
            R.id.layout_phone_number,
            R.id.layout_grzl, R.id.tv_login_out, R.id.layout_pay_pwd, R.id.layout_sh_info, R.id.layout_bind_zfb,
            R.id.layout_clear_cache})
    public void doClick(View view) {
        if (AntiShake.check(view.getId())) {    //判断是否多次点击
            return;
        }
        switch (view.getId()) {
            case R.id.layout_setting_wx:
                //设置微信
                new StartActivityUtil(mContext, MyInfoSettingActivity.class).putExtra(Constants.SETTING_TYPE, 1)
                        .startActivity(true);
                break;
            case R.id.layout_bind_wx:
                //绑定微信
                RealmHelper realmHelper = App.getAppComponent().realmHelper();
                UserInfoResponBean userInfoResponBean = realmHelper.getUserInfoResponBean();
                if (userInfoResponBean != null && userInfoResponBean.getIs_bind_wx() == 1) {
                    //提示是否取消绑定微信
                    unBindWx();
                } else {
                    //绑定微信
                    getWxInfo();
                }
                break;
            case R.id.layout_nickname:
                //设置昵称
                new StartActivityUtil(mContext, MyInfoSettingActivity.class).putExtra(Constants.SETTING_TYPE, 2)
                        .startActivity(true);
                break;
            case R.id.layout_hide_set:
                //隐私设置
                new StartActivityUtil(mContext, PrivateSettingActivity.class)
                        .startActivity(true);
                break;
            case R.id.layout_phone_number:
                //修改手机号
                new StartActivityUtil(mContext, ChangeBodyWithCodeActivity.class).putExtra(Constants.SETTING_TYPE, 4)
                        .startActivity(true);
                break;
            case R.id.layout_sh_info:
                //收货信息
                new StartActivityUtil(mContext, ShopAddressListActivity.class).startActivity(true);
                break;
            case R.id.layout_grzl:
                //个人资料
                headUrl = "";
                setUserAvater();
                break;
            case R.id.layout_pay_pwd:
                //设置支付密码
                new StartActivityUtil(mContext, ChangeBodyWithCodeActivity.class).putExtra(Constants.SETTING_TYPE, 2)
                        .startActivity(true);
                break;
            case R.id.layout_bind_zfb:
                //设置支付宝账号
                new StartActivityUtil(mContext, ChangeBodyWithCodeActivity.class).putExtra(Constants.SETTING_TYPE, 3)
                        .startActivity(true);
                break;
            case R.id.layout_login_pwd:
                //设置登录密码
                new StartActivityUtil(mContext, ChangeBodyWithCodeActivity.class).putExtra(Constants.SETTING_TYPE, 5)
                        .startActivity(true);
                break;
            case R.id.layout_vesion:
                //版本更新
                try {
                    LoadingDialogUtils.show(mContext);
                    PackageManager pm = mContext.getPackageManager();
                    PackageInfo pi = pm.getPackageInfo(mContext.getPackageName(), PackageManager.GET_ACTIVITIES);
                    mPresenter.getUpgradeInfo(pi.versionName, Constants.PHONE_TYPE);
                } catch (PackageManager.NameNotFoundException e) {
                    e.printStackTrace();
                }
                break;
            case R.id.layout_clear_cache:
                //清除缓存
                ACache.deleteDir(cacheFile);
                tvCacheText.setText(ACache.getCacheSize(cacheFile));
                StyleableToast.makeText(mContext, "缓存已清空", Toast.LENGTH_SHORT, R.style.mytoast).show();
                break;
            case R.id.tv_login_out:
                //退出登录
                try {
                    if (customBasePopup != null) {
                        customBasePopup.showPopupWindow();
                        return;
                    }
                    customBasePopup = new CustomBasePopup(mContext, "是否退出登录？", "", "",
                            new CustomBasePopup.PopupWindowCallback() {
                                @Override
                                public void sureClickCallback() {
                                    try {
//                                        deleteJpushAlias();

                                        ImplPreferencesHelper mImplPreferencesHelper = App.getAppComponent().preferencesHelper();
                                        mImplPreferencesHelper.setToken("");
                                        //清除用户信息
                                        mPresenter.clearUserInfo();

                                        App.getInstance().finishActivity();
                                        Intent intent = new Intent(mContext, LoginMainActivity.class);
                                        intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
                                        startActivity(intent);

                                    } catch (Exception e) {
                                        e.printStackTrace();
                                    }
                                }

                                @Override
                                public void cancelClickCallback() {

                                }
                            });
                    customBasePopup.setPopupGravity(Gravity.CENTER);
                    customBasePopup.showPopupWindow();

                } catch (Exception e) {
                    e.printStackTrace();
                }
                break;
            default:
                break;
        }
    }

    /**
     * 删除极光alias
     */
    private void deleteJpushAlias() {
        RealmHelper realmHelper = App.getAppComponent().realmHelper();
        UserInfoResponBean userInfoResponBean = realmHelper.getUserInfoResponBean();
        TagAliasOperatorHelper.TagAliasBean tagAliasBean = new TagAliasOperatorHelper.TagAliasBean();
        tagAliasBean.setAction(ACTION_DELETE);
        sequence++;
        tagAliasBean.setAlias(userInfoResponBean.getMobile());
        tagAliasBean.setAliasAction(true);
        TagAliasOperatorHelper.getInstance().handleAction(getApplicationContext(), sequence, tagAliasBean);
    }

    /**
     * 解绑微信
     */
    private void unBindWx() {
        if (unbindwxBasePopup != null) {
            unbindwxBasePopup.showPopupWindow();
            return;
        }
        unbindwxBasePopup = new UnbindwxBasePopup(mContext,
                new PopupItemClickCallback() {
                    @Override
                    public void onSureCallback(String text) {
                        //解绑微信
                        LoadingDialogUtils.show(mContext);
                        mPresenter.unBindWx("1");
                    }

                    @Override
                    public void onTextChangedCallback(String text) {

                    }
                });
        unbindwxBasePopup.setPopupGravity(Gravity.CENTER);
        unbindwxBasePopup.showPopupWindow();
    }

    /**
     * 获取微信信息
     */
    public void getWxInfo() {
        UMShareAPI api = UMShareAPI.get(this);
        UMShareConfig config = new UMShareConfig();
        config.isNeedAuthOnGetUserInfo(true);
        api.setShareConfig(config);
        api.getPlatformInfo(mContext, SHARE_MEDIA.WEIXIN, new UMAuthListener() {
            @Override
            public void onStart(SHARE_MEDIA share_media) {
                LoadingDialogUtils.show(mContext);
            }

            @Override
            public void onComplete(SHARE_MEDIA share_media, int i, Map<String, String> map) {
                if (map == null || TextUtils.isEmpty(map.get("unionid"))) {
                    LoadingDialogUtils.dismissDialog_ios();
                    StyleableToast.makeText(mContext, "获取微信信息失败", Toast.LENGTH_SHORT, R.style.mytoast).show();
                    return;
                }
                String mUnionid = map.get("unionid");
                String mNickname = map.get("name");
                String mHeadimgurl = map.get("iconurl");
                mPresenter.bindWx(mUnionid, mHeadimgurl, mNickname);
            }

            @Override
            public void onError(SHARE_MEDIA share_media, int i, Throwable throwable) {
                LoadingDialogUtils.dismissDialog_ios();
            }

            @Override
            public void onCancel(SHARE_MEDIA share_media, int i) {
                LoadingDialogUtils.dismissDialog_ios();
            }
        });

    }

    /**
     * 修改用户头像
     */
    private void setUserAvater() {

        if (picSelectedPopup != null) {
            picSelectedPopup.showPopupWindow();
            return;
        }
        picSelectedPopup = new PicSelectedPopup(mContext,
                new PicSelectedPopup.PicSelectedPopupCallback() {
                    @Override
                    public void cameraClickCallback() {
                        //拍照   PictureConfig.CHOOSE_REQUEST
                        PictureSelector.create(mContext)
                                .openCamera(PictureMimeType.ofImage())
                                .forResult(new OnResultCallbackListener() {
                                    @Override
                                    public void onResult(List<LocalMedia> result) {
                                        if (result == null || result.size() == 0) {
                                            return;
                                        }
                                        if (Build.VERSION.SDK_INT >= 29) {
                                            headUrl = result.get(0).getRealPath();
                                        } else {
                                            headUrl = result.get(0).getPath();
                                        }

                                        LoadingDialogUtils.show(mContext);
                                        mPresenter.getOsstoken(Constants.PHONE_TYPE);
                                    }

                                    @Override
                                    public void onCancel() {
                                        LogUtil.i("PictureSelector Cancel");
                                    }
                                });

                    }

                    @Override
                    public void albumClickCallback() {
                        PictureSelector.create(mContext)
                                .openGallery(PictureMimeType.ofImage())// 全部.PictureMimeType.ofAll()、图片.ofImage()、视频.ofVideo()、音频.ofAudio()
                                .loadImageEngine(GlideEngine.createGlideEngine())// 外部传入图片加载引擎，必传项
                                .theme(R.style.picture_default_style)// 主题样式设置 具体参考 values/styles   用法：R.style.picture.white.style v2.3.3后 建议使用setPictureStyle()动态方式
                                .isWeChatStyle(false)// 是否开启微信图片选择风格
                                .isUseCustomCamera(false)// 是否使用自定义相机
//                              .setLanguage(language)// 设置语言，默认中文
                                .setPictureStyle(mPictureParameterStyle)// 动态自定义相册主题
//                              .setPictureCropStyle(mCropParameterStyle)// 动态自定义裁剪主题
//                             .setPictureWindowAnimationStyle(mWindowAnimationStyle)// 自定义相册启动退出动画
//                             .isWithVideoImage(true)// 图片和视频是否可以同选,只在ofAll模式下有效
                                //.setButtonFeatures(CustomCameraView.BUTTON_STATE_BOTH)// 设置自定义相机按钮状态
                                .maxSelectNum(1)// 最大图片选择数量
                                .minSelectNum(1)// 最小选择数量
                                .maxVideoSelectNum(1) // 视频最大选择数量，如果没有单独设置的需求则可以不设置，同用maxSelectNum字段
                                //.minVideoSelectNum(1)// 视频最小选择数量，如果没有单独设置的需求则可以不设置，同用minSelectNum字段
                                .imageSpanCount(4)// 每行显示个数
                                .isReturnEmpty(false)// 未选择数据时点击按钮是否可以返回
                                //.isAndroidQTransform(false)// 是否需要处理Android Q 拷贝至应用沙盒的操作，只针对compress(false); && enableCrop(false);有效,默认处理
                                .setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT)// 设置相册Activity方向，不设置默认使用系统
                                .isOriginalImageControl(false)// 是否显示原图控制按钮，如果设置为true则用户可以自由选择是否使用原图，压缩、裁剪功能将会失效
                                //.bindCustomPlayVideoCallback(callback)// 自定义视频播放回调控制，用户可以使用自己的视频播放界面
                                //.cameraFileName(System.currentTimeMillis() +".jpg")    // 重命名拍照文件名、如果是相册拍照则内部会自动拼上当前时间戳防止重复，注意这个只在使用相机时可以使用，如果使用相机又开启了压缩或裁剪 需要配合压缩和裁剪文件名api
                                //.renameCompressFile(System.currentTimeMillis() +".jpg")// 重命名压缩文件名、 注意这个不要重复，只适用于单张图压缩使用
                                //.renameCropFileName(System.currentTimeMillis() + ".jpg")// 重命名裁剪文件名、 注意这个不要重复，只适用于单张图裁剪使用
                                .selectionMode(PictureConfig.MULTIPLE)// 多选 or 单选
//                              .isSingleDirectReturn(cb_single_back.isChecked())// 单选模式下是否直接返回，PictureConfig.SINGLE模式下有效
                                .previewImage(true)// 是否可预览图片
                                .previewVideo(true)// 是否可预览视频
//                                .selectionMedia(mAdapter.getData())// 是否传入已选图片
                                .enablePreviewAudio(true) // 是否可播放音频
                                .isCamera(true)// 是否显示拍照按钮
                                //.isMultipleSkipCrop(false)// 多图裁剪时是否支持跳过，默认支持
                                //.isMultipleRecyclerAnimation(false)// 多图裁剪底部列表显示动画效果
                                .isZoomAnim(true)// 图片列表点击 缩放效果 默认true
                                .compress(true)// 是否压缩
                                //.compressQuality(80)// 图片压缩后输出质量 0~ 100
                                .synOrAsy(true)//同步true或异步false 压缩 默认同步
                                .isGif(false)// 是否显示gif图片
                                .cutOutQuality(90)// 裁剪输出质量 默认100
                                .minimumCompressSize(100)// 小于100kb的图片不压缩
                                .forResult(new OnResultCallbackListener() {
                                    @Override
                                    public void onResult(List<LocalMedia> result) {
                                        if (result == null || result.size() == 0) {
                                            return;
                                        }
                                        if (Build.VERSION.SDK_INT >= 29) {
                                            headUrl = result.get(0).getRealPath();
                                        } else {
                                            headUrl = result.get(0).getPath();
                                        }
                                        LoadingDialogUtils.show(mContext);
                                        mPresenter.getOsstoken(Constants.PHONE_TYPE);
                                    }

                                    @Override
                                    public void onCancel() {
                                        LogUtil.i("PictureSelector Cancel");
                                    }
                                });
                    }
                });

        //弹框执行动画
        float fromX = 0;
        float fromY = 1f;
        float toX = 0;
        float toY = 0;
        Animation showAnimation = createTranslateAnimation(fromX, toX, fromY, toY);
        Animation dismissAnimation = createTranslateAnimation(toX, fromX, toY, fromY);
        picSelectedPopup.setShowAnimation(showAnimation);
        picSelectedPopup.setDismissAnimation(dismissAnimation);
        picSelectedPopup.setPopupGravity(Gravity.BOTTOM);
        picSelectedPopup.showPopupWindow();
    }

    @Override
    protected int getTitleIntText() {
        return R.string.setting_title;
    }

    @Override
    protected void initImmersionBar() {
        super.initImmersionBar();
        ImmersionBar.with(this)
                .titleBar(mToolbar, true)
                .statusBarDarkFont(true)
                .init();
    }

    @Override
    protected void initInject() {
        getActivityComponent().inject(this);
    }

    @Override
    public void showContent(String list) {

    }

    @Override
    public void showUserInfo(UserInfoResponBean bean) {
//        this.userInfoResponBean = bean;
        if (bean != null) {
            tvNicknameLab.setText(TextUtils.isEmpty(bean.getNickname()) ? "" : bean.getNickname());
            Glide.with(mContext).load(bean.getHeadimg()).placeholder(R.mipmap.icon_default_head).error(R.mipmap.icon_default_head).skipMemoryCache(true).diskCacheStrategy(DiskCacheStrategy.NONE).into(rivUserHead);
            tvPhoneNumberLab.setText(TextUtils.isEmpty(bean.getMobile()) ? getString(R.string.setting_no_set) : bean.getMobile());
            tvPayPassword.setText(bean.getIs_password() == 1 ? getString(R.string.setting_have_set) : getString(R.string.setting_no_set));
            tvBindzfbLab.setText(bean.getIs_alipay() == 1 ? getString(R.string.setting_have_set) : getString(R.string.setting_no_set));
            tvLoginPwdLab.setText(bean.getIs_pwd() == 1 ? getString(R.string.setting_have_set) : getString(R.string.setting_no_set));
            tvSettingwxLab.setText(TextUtils.isEmpty(bean.getWx_card()) ? getString(R.string.setting_no_set) : bean.getWx_card());
            tvBindwxLab.setText(bean.getIs_bind_wx() == 1 ? getString(R.string.setting_have_set) : getString(R.string.setting_no_set));
//            tvShInfoLab.setText(getString(R.string.setting_no_set));
        }

    }

    @Override
    public void showUserInfoError() {

    }

    @Override
    public void settingAvaterSuccess() {
        //设置头像成功
        LoadingDialogUtils.dismissDialog_ios();
        StyleableToast.makeText(mContext, "设置成功", Toast.LENGTH_SHORT, R.style.mytoast).show();
        //刷新用户信息
        RxBus.getDefault().post(new SendEvent("", Constants.TYPE_GET_USERINFO));
    }

    @Override
    public void bindWxSuccess() {
        //绑定微信成功
        LoadingDialogUtils.dismissDialog_ios();
        StyleableToast.makeText(mContext, "绑定成功", Toast.LENGTH_SHORT, R.style.mytoast).show();
        //刷新用户信息
        RxBus.getDefault().post(new SendEvent("", Constants.TYPE_GET_USERINFO));
    }

    @Override
    public void unBindWxSuccess() {
        //解绑成功
        LoadingDialogUtils.dismissDialog_ios();
        StyleableToast.makeText(mContext, "解绑成功", Toast.LENGTH_SHORT, R.style.mytoast).show();
        //刷新用户信息
        RxBus.getDefault().post(new SendEvent("", Constants.TYPE_GET_USERINFO));
    }

    @Override
    public void showOsstoken(BaseResponse baseResponse) {
        //获取oss成功
        if (baseResponse == null) {
            StyleableToast.makeText(mContext, "无法上传图片", Toast.LENGTH_SHORT, R.style.mytoast).show();
            return;
        }
        upLoadImage(baseResponse);
    }

    @Override
    public void showLbImg(int type, List<LbImgBean> list) {

    }

    @Override
    public void showUpgradeInfo(VersionResponBean versionResponBean) {
        //更新信息
        LoadingDialogUtils.dismissDialog_ios();
        startUpdate(versionResponBean);
    }

    @Override
    public void showPtiorderStatus(OrderStatusResponBean orderStatusResponBean) {

    }


    private void startUpdate(VersionResponBean versionResponBean) {
        if (versionResponBean == null || versionResponBean.getIs_update() == 0) {
            StyleableToast.makeText(mContext, "当前已是最新版本", Toast.LENGTH_SHORT, R.style.mytoast).show();
            return;
        }
        /*
         * 整个库允许配置的内容
         */
        UpdateConfiguration configuration = new UpdateConfiguration()
                //输出错误日志
                .setEnableLog(false)
                //设置自定义的下载
                //.setHttpManager()
                //下载完成自动跳动安装页面
                .setJumpInstallPage(true)
                //设置对话框背景图片 (图片规范参照demo中的示例图)
                .setDialogImage(R.mipmap.icon_upgrad_dialog_bg)
                //设置按钮的颜色
                .setDialogButtonColor(Color.parseColor("#DA291C"))
                //设置对话框强制更新时进度条和文字的颜色
                .setDialogProgressBarColor(Color.parseColor("#DA291C"))
                //设置按钮的文字颜色
                .setDialogButtonTextColor(Color.WHITE)
                //设置是否显示通知栏进度
                .setShowNotification(true)
                //设置是否提示后台下载toast
                .setShowBgdToast(true)
                //设置强制更新
                .setForcedUpgrade(versionResponBean.getIs_more() == 1);
        //设置对话框按钮的点击监听
//                .setButtonClickListener(this)
        //设置下载过程的监听
//                .setOnDownloadListener(this);

        DownloadManager manager = DownloadManager.getInstance(this);
        manager.setApkName(TextUtils.isEmpty(versionResponBean.getApkName()) ? (System.currentTimeMillis() + ".apk") : versionResponBean.getApkName())
                .setApkUrl(versionResponBean.getDownload_url())
                .setSmallIcon(R.mipmap.icon_logo)
                .setShowNewerToast(true)
                .setConfiguration(configuration)
                .setApkVersionCode(versionResponBean.getVersionCode())
                .setApkVersionName(versionResponBean.getVersion())
                .setApkSize(versionResponBean.getApkSize())
                .setApkDescription(versionResponBean.getContent())
                .download();
    }


    public void upLoadImage(BaseResponse baseResponse) {
        //初始化
        OssManager.getInstance().init(this, Constants.OSS_ENDPOINT, baseResponse.getAccessKeyId(), baseResponse.getAccessKeySecret(), baseResponse.getSecurityToken(), mUpLoadCallback);
        upImageToOss(headUrl);
    }

    private void getDefaultStyle() {
        // 相册主题
        mPictureParameterStyle = new PictureParameterStyle();
        // 是否改变状态栏字体颜色(黑白切换)
        mPictureParameterStyle.isChangeStatusBarFontColor = false;
        // 是否开启右下角已完成(0/9)风格
        mPictureParameterStyle.isOpenCompletedNumStyle = false;
        // 是否开启类似QQ相册带数字选择风格
        mPictureParameterStyle.isOpenCheckNumStyle = false;
        // 相册状态栏背景色
        mPictureParameterStyle.pictureStatusBarColor = Color.parseColor("#393a3e");
        // 相册列表标题栏背景色
        mPictureParameterStyle.pictureTitleBarBackgroundColor = Color.parseColor("#393a3e");
        // 相册列表标题栏右侧上拉箭头
        mPictureParameterStyle.pictureTitleUpResId = R.drawable.picture_icon_arrow_up;
        // 相册列表标题栏右侧下拉箭头
        mPictureParameterStyle.pictureTitleDownResId = R.drawable.picture_icon_arrow_down;
        // 相册文件夹列表选中圆点
        mPictureParameterStyle.pictureFolderCheckedDotStyle = R.drawable.picture_orange_oval;
        // 相册返回箭头
        mPictureParameterStyle.pictureLeftBackIcon = R.drawable.picture_icon_back;
        // 标题栏字体颜色
        mPictureParameterStyle.pictureTitleTextColor = ContextCompat.getColor(mContext, R.color.picture_color_white);
        // 相册右侧取消按钮字体颜色  废弃 改用.pictureRightDefaultTextColor和.pictureRightDefaultTextColor
        mPictureParameterStyle.pictureCancelTextColor = ContextCompat.getColor(mContext, R.color.picture_color_white);
        // 相册列表勾选图片样式
        mPictureParameterStyle.pictureCheckedStyle = R.drawable.picture_checkbox_selector;
        // 相册列表底部背景色
        mPictureParameterStyle.pictureBottomBgColor = ContextCompat.getColor(mContext, R.color.picture_color_grey);
        // 已选数量圆点背景样式
        mPictureParameterStyle.pictureCheckNumBgStyle = R.drawable.picture_num_oval;
        // 相册列表底下预览文字色值(预览按钮可点击时的色值)
        mPictureParameterStyle.picturePreviewTextColor = ContextCompat.getColor(mContext, R.color.picture_color_fa632d);
        // 相册列表底下不可预览文字色值(预览按钮不可点击时的色值)
        mPictureParameterStyle.pictureUnPreviewTextColor = ContextCompat.getColor(mContext, R.color.picture_color_white);
        // 相册列表已完成色值(已完成 可点击色值)
        mPictureParameterStyle.pictureCompleteTextColor = ContextCompat.getColor(mContext, R.color.picture_color_fa632d);
        // 相册列表未完成色值(请选择 不可点击色值)
        mPictureParameterStyle.pictureUnCompleteTextColor = ContextCompat.getColor(mContext, R.color.picture_color_white);
        // 预览界面底部背景色
        mPictureParameterStyle.picturePreviewBottomBgColor = ContextCompat.getColor(mContext, R.color.picture_color_grey);
        // 外部预览界面删除按钮样式
        mPictureParameterStyle.pictureExternalPreviewDeleteStyle = R.drawable.picture_icon_delete;
        // 原图按钮勾选样式  需设置.isOriginalImageControl(true); 才有效
        mPictureParameterStyle.pictureOriginalControlStyle = R.drawable.picture_original_wechat_checkbox;
        // 原图文字颜色 需设置.isOriginalImageControl(true); 才有效
        mPictureParameterStyle.pictureOriginalFontColor = ContextCompat.getColor(mContext, R.color.white);
        // 外部预览界面是否显示删除按钮
        mPictureParameterStyle.pictureExternalPreviewGonePreviewDelete = true;
        // 设置NavBar Color SDK Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP有效
        mPictureParameterStyle.pictureNavBarColor = Color.parseColor("#393a3e");
    }

    /**
     * 清空缓存包括裁剪、压缩、AndroidQToPath所生成的文件，注意调用时机必须是处理完本身的业务逻辑后调用；非强制性
     */
    private void clearCache() {
        // 清空图片缓存，包括裁剪、压缩后的图片 注意:必须要在上传完成后调用 必须要获取权限
        if (PermissionChecker.checkSelfPermission(mContext, Manifest.permission.WRITE_EXTERNAL_STORAGE)) {
            //PictureFileUtils.deleteCacheDirFile(this, PictureMimeType.ofImage());
            PictureFileUtils.deleteAllCacheDirFile(mContext);
        } else {
            PermissionChecker.requestPermissions(this, new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE},
                    PictureConfig.APPLY_STORAGE_PERMISSIONS_CODE);
        }
    }


    /**
     * 上传图片到oss
     *
     * @param mPath
     */
    public void upImageToOss(String mPath) {
        String objectKey = "upload" + "/" + DateUtils.getCreateFileName("IMG_") + PictureMimeType.getLastImgSuffix(mPath);
        OssManager.getInstance().upLoadImage(objectKey, mPath);
    }


    private OssManager.UpLoadCallback mUpLoadCallback = new OssManager.UpLoadCallback() {

        @Override
        public void loadSuccess(String resultUrl) {
            //上传头像
            mPresenter.settingAvater(Constants.OSS_BASE_URL + resultUrl);
        }

        @Override
        public void loadFail() {
            LoadingDialogUtils.dismissDialog_ios();
            StyleableToast.makeText(mContext, "修改失败", Toast.LENGTH_SHORT, R.style.mytoast).show();
        }
    };
//    @Override
//    public void onButtonClick(int id) {
//
//    }
//
//    @Override
//    public void start() {
//
//    }
//
//    @Override
//    public void downloading(int max, int progress) {
//
//    }
//
//    @Override
//    public void done(File apk) {
//
//    }
//
//    @Override
//    public void cancel() {
//
//    }
//
//    @Override
//    public void error(Exception e) {
//
//    }
}
